package com.mmall.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Synchronized 锁
 * Created by megan on 2018/3/21.
 */
@Slf4j
public class SynchronizedExample2 {

    /**
     * 修饰类
     * 作用对象为这个类的所有对象
     */
    public static void test1(int j){
        synchronized (SynchronizedExample2.class){
            for(int i = 0,b = 10; i<b ; i++){
                log.info("test1 {} --> {}",j,i);
            }
        }
    }

    /**
     * 修饰静态方法
     * 作用对象为这个类的所有对象
     */
    public static synchronized void test2(int j){
        for(int i = 0,b = 10; i<b ; i++){
            log.info("test2 {} --> {}",j,i);
        }
    }

    public static void main(String[] args) {
        //声明一个线程池
        ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>(), r -> new Thread(r,"测试线程(Synchronized1)"));
        executorService.execute(() -> {
            test2(1);
        });
        executorService.execute(() -> {
            test2(2);
        });
    }
}
